package com.weimob.mcloud.wechatwork.customer.mq.model;

import com.weimob.mcloud.wechatwork.core.entity.privatesphere.PrivateSphere;
import com.weimob.mcloud.wechatwork.core.entity.relation.group.CustomerGroup;
import com.weimob.mcloud.wechatwork.core.entity.relation.group.CustomerGroupMember;
import com.weimob.mcloud.wechatwork.core.enums.customer.CustomerStatusEnum;
import com.weimob.mcloud.wechatwork.core.enums.group.GroupMemberTypeEnum;
import com.weimob.mcloud.wechatwork.core.service.group.request.CustomerGroupMemberDTO;
import com.weimob.mcloud.wechatwork.customer.facade.impl.customer.CustomerFacade;
import com.weimob.mcloud.wechatwork.customer.service.user.base.BasicInfo;
import com.weimob.mcloud.wechatwork.customer.service.user.base.PageResponse;
import com.weimob.mcloud.wechatwork.customer.service.user.module.bo.customer.ExternalUserListBO;
import com.weimob.mcloud.wechatwork.customer.service.user.module.dto.customer.ExternalUserInfoFindDTO;
import com.weimob.mcloud.wechatwork.customer.third.core.CustomerGroupExportServiceProxy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author liuzhu.chen
 * @Description
 * @Date 2022/4/21 15:40
 * @Version 1.0
 */

@Service
@Slf4j
public class CustomerGroupStatisticServiceImpl {

    @Resource
    RedisTemplate<String, String> redisTemplate;

    @Resource
    CustomerFacade customerFacade;

    @Value("${statistic.non.friend.task:false}")
    Boolean statisticNonFriendTask;

    @Resource
    private CustomerGroupExportServiceProxy customerGroupExportServiceProxy;

    /**
     * 更新群成员表好友标识
     *
     * @param customerList  群成员列表
     * @param privateSphere 私域
     */
    public void updateFriendIdentification(List<CustomerGroupMemberDTO> customerList, PrivateSphere privateSphere) {
        if (CollectionUtils.isEmpty(customerList)) {
            return;
        }

        // 1、allExternalUserIdList
        String corpId = customerList.get(0).getCorpId();
        String groupId = customerList.get(0).getGroupId();
        List<String> allExternalUserIdList = customerList.stream()
                .filter(e -> GroupMemberTypeEnum.EXTERNAL_USER.getCode().equals(e.getType()))
                .map(CustomerGroupMemberDTO::getMemberId)
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(allExternalUserIdList)) {
            return;
        }

        // 2、批量判断好友关系
        List<String> friendIdList = new ArrayList<>();
        fillFriendExternalUserIdList(privateSphere, allExternalUserIdList, friendIdList);

        // 3、批量更新好友标识-好友
        CustomerGroup customerGroup = new CustomerGroup();
        customerGroup.setGroupId(groupId);
        CustomerGroupMember customerGroupMember = new CustomerGroupMember();
        customerGroupMember.setCustomerGroup(customerGroup);
        customerGroupMember.setPrivateSphere(privateSphere);
        customerGroupMember.setIsFriend(1);
        customerGroupMember.setGroupMemberType(GroupMemberTypeEnum.EXTERNAL_USER);
        HashMap<String, Object> extInfo = new HashMap<>();
        extInfo.put("memberIdList", allExternalUserIdList);
        customerGroupExportServiceProxy.updateMemberFriendStatus(customerGroupMember,extInfo);

        // 4、批量更新好友标识-非好友
        if (CollectionUtils.isNotEmpty(friendIdList)) {
            allExternalUserIdList.removeAll(friendIdList);
        }
        if (CollectionUtils.isEmpty(allExternalUserIdList)) {
            return;
        }
        customerGroupMember.setIsFriend(0);
        extInfo.put("memberIdList", allExternalUserIdList);
        customerGroupExportServiceProxy.updateMemberFriendStatus(customerGroupMember,extInfo);
    }

    /**
     * 填充有好友关系的externalUserId
     *
     * @param privateSphere            私域
     * @param allExternalUserIdList    allExternalUserIdList
     * @param friendExternalUserIdList friendExternalUserIdList
     */
    private void fillFriendExternalUserIdList(PrivateSphere privateSphere, List<String> allExternalUserIdList, List<String> friendExternalUserIdList) {
        ExternalUserInfoFindDTO externalUserInfoFindDTO = new ExternalUserInfoFindDTO();
        int pageNum = 0;
        int pageSize = 100;
        externalUserInfoFindDTO.setPageSize(pageSize);
        externalUserInfoFindDTO.setFollowStatus(false);
        externalUserInfoFindDTO.setExternalUserIds(allExternalUserIdList);
        externalUserInfoFindDTO.setStatus(CustomerStatusEnum.DEFAULT.getCode());
        BasicInfo basicInfo = new BasicInfo();
        basicInfo.setCorpId(privateSphere.getCorpId());
        basicInfo.setBosId(privateSphere.getBosId());
        basicInfo.setProductId(privateSphere.getProductId());
        basicInfo.setProductInstanceId(privateSphere.getProductInstanceId());
        basicInfo.setProductVersionId(privateSphere.getProductVersionId());
        externalUserInfoFindDTO.setBasicInfo(basicInfo);
        PageResponse<ExternalUserListBO> pageResponse;
        do {
            pageNum++;
            externalUserInfoFindDTO.setPageNum(pageNum);
            pageResponse = customerFacade.getExternalUserBySearch(externalUserInfoFindDTO);
            List<ExternalUserListBO> externalUserList = pageResponse.getResults();
            if (CollectionUtils.isNotEmpty(externalUserList)) {
                List<String> externalUserIds = externalUserList.stream().map(ExternalUserListBO::getExternalUserId).collect(Collectors.toList());
                if (CollectionUtils.isNotEmpty(externalUserIds)) {
                    friendExternalUserIdList.addAll(externalUserIds);
                }
            }
        } while (Objects.nonNull(pageResponse.getTotalCount()) && (long) pageNum * pageSize < pageResponse.getTotalCount());
    }

}